import { onMounted, onUnmounted, ref } from 'vue'

/**
 * @description 获取浏览器窗口滚动条位置
 * @function useWindowScroll()
 * @return object = { x, y }
 * @example
   <script setup lang="ts">
     const { x, y } = useWindowScroll()
   </script>

   <template>
     <div>scroll: {{x}}, {{y}}</div>
   </template>
 */
export const useWindowScroll = () => {
  if (!window) {
    return {
      x: ref(0),
      y: ref(0)
    }
  }
  const x = ref(window.scrollX || window.pageXOffset)
  const y = ref(window.scrollY || window.pageYOffset)

  const getWindowScroll = () => {
    x.value = window.scrollX || window.pageXOffset
    y.value = window.scrollY || window.pageYOffset
  }

  onMounted(() => {
    window.addEventListener('scroll', getWindowScroll)
  })
  onUnmounted(() => {
    window.removeEventListener('scroll', getWindowScroll)
  })

  return {
    x,
    y
  }
}
